#!/usr/bin/env python

#
# The MIT License
#
# Copyright (c) 2008 Nicholas Galbreath
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

"""
Command line interface to copying files to and from s3
"""


# all of this can be cleaned up
import sys
import boto
import os
import os.path
import stat
from optparse import  OptionParser
from urlparse import urlparse
from boto.s3.connection import S3Connection

from progress_monitor import ProgressMonitor
from funnel.utils.s3helpers import s3_download

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-a', '--acl', dest='acl', default='public-read',
                      action='store_true',
                      help="one of 'private', 'public-read', 'public-read-write', 'authenticated-read'")
    parser.add_option('-f', '--force', action="store_true",
                      dest='force', default=False,
                      help='overwrite')

    options,args = parser.parse_args()

    filefrom = args[0]

    filefroms3 = False
    filefromparts = None
    if filefrom.startswith('s3:/'):
        filefroms3 = True
        filefromparts = urlparse(filefrom.replace('s3', 'http'))
    else:
        filefromparts = urlparse(filefrom)
    
    fileto = None
    filetos3 = False
    filetoparts = None
    if len(args) > 1:
        fileto   = args[1]
        if fileto.startswith('s3'):
            filetoparts = urlparse(fileto.replace('s3', 'http'))
            filetos3 = True
        else:
            filetoparts = urlparse(fileto)

    #
    # various cases
    #
    # from is s3, and to is not:
    #   download
    if filefroms3 is True and filetos3 is False:
        s3_download(filefrom, fileto, options.force)

    # from is not s3, and to is s3
    #  upload local file to s3
    #    
    elif filefroms3 is False and filetos3 is True:
        bucketname = filetoparts[1]
        fullfile   = filetoparts[2].strip('/').strip(' ')

        # case where  cp FILE DIR is actually cp FILE DIR/FILE
        if len(fullfile) == 0:
            fullfile = os.path.basename(filefromparts[2])
            fileto = fileto.strip('/') + '/' + fullfile

        sys.stderr.write("Uploading %s to %s\n" % (filefrom, fileto))

        acl = options.acl
        con = S3Connection()
        bucket = con.get_bucket(bucketname)
        akey = bucket.get_key(fullfile)

        if akey is None:
            akey = bucket.new_key(fullfile)
        
        p = ProgressMonitor(filefrom)
        
        akey.set_contents_from_filename(filefrom, headers=None, replace=True,
                                        cb=p.update, num_cb=1000)
        akey.set_acl(acl)

    else:
        sys.stderr.write("Not supported\n")
        sys.stderr.write("filefroms3 = " + str(filefroms3))
        sys.stderr.write("filetos3 = " + str(filetos3))
        sys.exit(1)

